package com.cn.dao;

import static java.lang.Class.forName;

import java.util.*;
import java.sql.*;

public class BaseDao {

	static Connection conn;
	static Statement stmt;
	static ResultSet rs;
	static PreparedStatement prestmt;
	
	public Connection getConn()
	{
		String driver="com.mysql.jdbc.Driver";
		String url="jdbc:mysql://localhost:3306/kaoshi";
		try
		{
			forName(driver);
			conn=DriverManager.getConnection(url,"root","123456");
		}catch(Exception e){
			e.printStackTrace();
		}
		return conn;
	}
	
	
	
	protected int executeUpdate(String sql ,String[]params)
	{ 
		int num=-1; 
		try 
		{ 
			this.getConn(); 
			this.prestmt=this.conn.prepareStatement(sql); 
			if(null!=params)
			{ 
				for (int i = 0; i < params.length; i++) 
				{ 
					this.prestmt.setString(i+1, params[i]); 
				}  
			} 
			num= this.prestmt.executeUpdate(); 
		} catch (Exception e)
		{ 
			e.printStackTrace(); 
		}finally{
				this.close();
		}
		return num; 
	} 
		/** 
		* ��ѯ���ķ��� 
		* @param sql 
		* @param params 
		*/
	
	
		protected ResultSet executeQuery(String sql,String[] params)
		{ 
			try 
			{ 
				this.getConn(); 
				this.prestmt=this.conn.prepareStatement(sql); 
				if(params!=null)
				{ 
					for (int i = 0; i < params.length; i++) 
					{ 
						this.prestmt.setString(i+1, params[i]); 
					}  
				} 
				this.rs=this.prestmt.executeQuery();

			} catch (Exception e) 
			{ 
				e.printStackTrace(); 
			}
			
			return rs;
		}
		 /**
	     *关闭数据库的操作对象 
	     */
	    public void close(){
	    	try {
				//关闭结果集
	    		if (rs!=null){
	    			rs.close();
	    		} 
	    		//关闭sql语句的发布对象
	    		if (prestmt!=null){
	    			prestmt.close();
	    		}
	    		//关闭sql语句的发布对象
	    		if (stmt!=null){
	    			stmt.close();
	    		}
	    		//关闭数据库连接
	    		if (conn!=null){
	    			conn.close();
	    		}
			} catch (Exception e) {
				// TODO: handle exception
			}
	    }
}
